﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Clipping.Infrastructure.Models;
using System.Collections.ObjectModel;
using System.Diagnostics;
using System.Text.RegularExpressions;

namespace ClippingEditor
{
    class MediaFieldViewModel : FieldViewModel
    {

        static List<MediaInfo> AllMedias;
        static MediaFieldViewModel()
        {
            Clipping.Utils.MediaInfoProvider mp = Clipping.Utils.MediaInfoProvider.GetInstance();
            AllMedias = mp.GetAllMediaInfo();
        }

        public MediaFieldViewModel(Field field, string value)
            : base(field, value)
        {
            this.FilteredMedias = new ObservableCollection<MediaInfo>();
            this.PropertyChanged += new System.ComponentModel.PropertyChangedEventHandler(MediaFieldViewModel_PropertyChanged);

            //this.SelectMedia = AllMedias.FirstOrDefault(m => m.Name == this.Value || string.Equals(m.Url, this.Value, StringComparison.OrdinalIgnoreCase));
        }

        void MediaFieldViewModel_PropertyChanged(object sender, System.ComponentModel.PropertyChangedEventArgs e)
        {
            if (e.PropertyName == "Value")
            {
                this.SelectMedia = AllMedias.FirstOrDefault(m => m.Name == this.Value || string.Equals(m.Url, this.Value, StringComparison.OrdinalIgnoreCase));
            }
        }


        private ObservableCollection<MediaInfo> _filteredMedias;

        public ObservableCollection<MediaInfo> FilteredMedias
        {
            get { return _filteredMedias; }
            set
            {
                _filteredMedias = value;
                RaisePropertyChanged(() => this.FilteredMedias);
            }
        }



        private MediaInfo _selectMedia;
        /// <summary>
        /// 选择的商品
        /// </summary>
        public MediaInfo SelectMedia
        {
            get { return _selectMedia; }
            set
            {
                if (_selectMedia == value)
                    return;
                _selectMedia = value;
                if (value != null)
                    this.Value = value.Name;
                else
                    this.Value = null;
                RaisePropertyChanged(() => this.SelectMedia);
            }
        }


        public void TrySetMedia(string mediaName, string url)
        {
            var media = AllMedias.FirstOrDefault(m => m.Name == mediaName);
            if (media != null)
            {
                this.SelectMedia = media;
                return;
            }

            media = AllMedias.FirstOrDefault(m => string.Equals(m.Url, mediaName, StringComparison.OrdinalIgnoreCase));

            if (media != null)
            {
                this.SelectMedia = media;
                return;
            }


            if (!string.IsNullOrEmpty(url))
            {
                Match match = Regex.Match(url, "https?://([^/]+)", RegexOptions.IgnoreCase);
                if (match.Success)
                {
                    media = AllMedias.FirstOrDefault(m => string.Equals(m.Url, match.Groups[1].Value, StringComparison.OrdinalIgnoreCase));

                    if (media != null)
                        this.SelectMedia = media;
                    else
                        this.SelectMedia = null;
                }
                else
                    this.SelectMedia = null;

            }


        }

        #region 条件过滤方法

        /// <summary>
        /// 条件过滤方法
        /// </summary>
        public Func<string, InputComboBox.OperationType, bool> MediaFilterAction
        {
            get
            {
                return new Func<string, InputComboBox.OperationType, bool>((cc, ot) =>
                {
                    return FindMediaByNameOrUrl(cc, ot);
                });
            }
        }

        private bool FindMediaByNameOrUrl(string cc, InputComboBox.OperationType ot)
        {
            this.FilteredMedias.Clear();
            foreach (var d in AllMedias)
            {
                if (d.Name.StartsWith(cc) || (!string.IsNullOrEmpty(d.Url) && d.Url.StartsWith(cc)))
                    this.FilteredMedias.Add(d);
            }
            return true;
        }

        #endregion


        #region 返回单一商品的方法

        /// <summary>
        /// 返回单一商品的方法
        /// </summary>
        public Func<string, InputComboBox.OperationType, object> GetMediaAction
        {
            get
            {
                return new Func<string, InputComboBox.OperationType, object>((cc, ot) =>
                {
                    return GetMedia(cc);
                });
            }
        }

        private object GetMedia(string cc)
        {
            if (string.IsNullOrEmpty(cc))
                return null;
            var query = AllMedias.Where(d => d.Name.StartsWith(cc) || (!string.IsNullOrEmpty(d.Url) && d.Url.StartsWith(cc)));
            if (query.Any())
                return query.First();
            else
            {
                return null;
            }
        }

        #endregion


        #region 失去焦点时的处理方法

        public Func<string, Tuple<bool, object>> LostFocusAction
        {
            get
            {
                return new Func<string, Tuple<bool, object>>((code) =>
                {
                    if (this.SelectMedia != null && SelectMedia.Name == code)
                        return new Tuple<bool, object>(false, SelectMedia);

                    MediaInfo result = AllMedias.Where(m => m.Name == code || string.Equals(m.Url, code, StringComparison.OrdinalIgnoreCase)).FirstOrDefault();

                    if (result != null)
                        return new Tuple<bool, object>(true, result);
                    else
                        return new Tuple<bool, object>(false, null);
                });
            }
        }

        #endregion


    }
}
